<template>
  <a-breadcrumb>
    <a-breadcrumb-item
      v-for="(item, index) in breadcrumbs"
      :key="item.path">
      <span
        v-if="item.redirect === 'noredirect' || index === breadcrumbs.length - 1"
        class="no-redirect"
        >{{item.meta.title}}</span>
        <a v-else>{{item.meta.title}}</a>
    </a-breadcrumb-item>
  </a-breadcrumb>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  onBeforeMount,
  watch,
} from 'vue';
import { Breadcrumb } from 'ant-design-vue';
import { useRoute, RouteLocationMatched } from 'vue-router';

export default defineComponent({
  name: 'BreadCrumb',
  components: {
    ABreadcrumb: Breadcrumb,
    ABreadcrumbItem: Breadcrumb.Item,
  },
  setup() {
    const currentRoute = useRoute();
    const state = reactive({
      breadcrumbs: [] as Array<RouteLocationMatched>,
      getBreadcrumb() {
        const matched = currentRoute.matched.filter((item) => item.meta && item.meta.title);
        state.breadcrumbs = matched.filter((item) => {
          const flag = item.meta && item.meta.title && item.meta.breadcrumb !== false;
          return flag;
        });
      },
    });

    watch(() => currentRoute.path, (path) => {
      if (path.startsWith('/redirect/')) {
        return;
      }
      state.getBreadcrumb();
    });

    onBeforeMount(() => {
      state.getBreadcrumb();
    });
    return {
      ...toRefs(state),
    };
  },
});
</script>
